package com.zyg.apart.controller;

import com.zyg.apart.model.Role;
import com.zyg.apart.service.UserService;
import com.zyg.apart.util.VerifyCodeUtil;
import com.zyg.apart.view.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/login")
public class LoginController {

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/lgPage")
    public String toLg(){
        return "login";
    }

    @RequestMapping("/lg")
    public String lg(Model model, LoginUser loginUser, HttpServletRequest request){
        //获取验证码
        String vCode = (String) request.getSession().getAttribute("vCode");

        if (!loginUser.getCode().equals(vCode)){
            model.addAttribute("error","验证码错误");
        }else{
            boolean flag = userService.login(loginUser,request);
            if (flag){
                Role role = userService.getRoleByName(loginUser.getUsername());
                model.addAttribute("role",role);
                return "forward:admin";
            }else{
                model.addAttribute("error","账号或密码错误");
            }

        }
        return "login";
    }

    @RequestMapping("/admin")
    public String admin(){
        return "admin";
    }


    @RequestMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletResponse response,HttpServletRequest request) throws IOException {
        VerifyCodeUtil VCU = new VerifyCodeUtil();
        BufferedImage image = VCU.getImage();
        request.getSession().setAttribute("vCode",VCU.getText());
        VerifyCodeUtil.output(image,response.getOutputStream());
    }

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}
